import { _decorator, Component, Node, Vec3 } from 'cc'
const { ccclass, property } = _decorator
import { FruitConfig } from './GameMgr'

enum FruitState {
	Ready = 1,
	Running = 2,
	Sliced = 3, // 切开
	Dead = 4,
}

@ccclass('FruitItem')
export class FruitItem extends Component {
	private config: FruitConfig = null
	private initScale: number = 0
	private deadLine: number = -11 // 水果死亡Y轴位置
	private state: FruitState = FruitState.Ready
	private vx: number = 0 // x轴速度
	private vy: number = 0 // y轴速度
	private gravity: number = -10 // 重力
	private wSpeed: number = 90 // 水果旋转速度  单位：度/秒

	update(deltaTime: number) {
		if (this.state === FruitState.Running) {
			this.fruitTotalUpdate(deltaTime)
		}
	}

	public initFruit(fruitConfig: FruitConfig): void {
		this.config = fruitConfig
		this.initScale = this.node.scale.x
		this.state = FruitState.Ready
		// 设置一些初始化的逻辑
		const scale = this.initScale * parseFloat(fruitConfig.scale)
		this.node.setScale(scale, scale, scale)
	}

	private fruitTotalUpdate(dt: number): void {
		// 水果抛物线运动的实现
		const pos = this.node.getPosition()
		pos.x += this.vx * dt
		pos.y += this.vy * dt + this.gravity * dt * dt * 0.5
		this.vy += this.gravity * dt
		this.node.setPosition(pos)

		// 销毁水果
		if (pos.y <= this.deadLine) {
			this.state = FruitState.Dead
			this.node.destroy()
		}

		// 水果围绕z轴自传
		const degree = this.wSpeed * dt
		const rot: Vec3 = this.node.eulerAngles
		rot.z += degree
		this.node.setRotationFromEuler(rot)
	}

	public throwFruitOut(force: Vec3): void {
		if (this.state !== FruitState.Ready) return

		this.vx = force.x * 0.1
		this.vy = force.y * 0.1
		this.state = FruitState.Running
	}
}
